from app import db


class Account(db.Model):
    __tablename__ = 'account_table'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    create_time = db.Column(db.DATETIME, index=True, unique=True)
    name = db.Column(db.String(256), index=True, unique=True)
    gate_key = db.Column(db.String(256), index=True, unique=True)
    gate_secret = db.Column(db.String(256), index=True, unique=True)
    password = db.Column(db.String(256), index=True, unique=True)
    contingent = db.Column(db.String(256), index=True, unique=True)

    def __repr__(self):
        return f'<Account {self.name}>'

    @classmethod
    def create_account(cls, name, gate_key, gate_secret, contingent):
        new_account = cls(name=name, gate_key=gate_key, gate_secret=gate_secret, contingent=contingent)
        db.session.add(new_account)
        try:
            db.session.commit()
            return new_account
        except Exception as e:
            db.session.rollback()
            raise e  # 重新抛出异常，以便在调用这个方法的地方可以处理它

    def delete(self):
        db.session.delete(self)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

    def update(self, name=None, gate_key=None, gate_secret=None, contingent=None):
        if name:
            self.name = name
        if gate_key:
            self.gate_key = gate_key
        if gate_secret:
            self.gate_secret = gate_secret
        if contingent:
            self.contingent = contingent

        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e


# models.py
from gate_api import Configuration, ApiClient, FuturesApi
from gate_api.exceptions import ApiException, GateApiException


def set_position_mode(gate_key, gate_secret, settle, dual_mode):
    configuration = Configuration(
        host="https://api.gateio.ws/api/v4",
        key=gate_key,
        secret=gate_secret
    )
    api_client = ApiClient(configuration)
    api_instance = FuturesApi(api_client)

    try:
        response = api_instance.set_dual_mode(settle, dual_mode)
        return {"code": 200, "data": response.to_dict(), "msg": "仓位模式设置成功"}
    except GateApiException as ex:
        return {"code": ex.status, "msg": f"Gate API异常, 标签: {ex.label}, 信息: {ex.message}"}
    except ApiException as e:
        return {"code": 500, "msg": f"API调用异常: {e}"}

